// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import axios from 'axios'

Vue.use(ElementUI)

// 配置axios
axios.defaults.timeout = 30000 // 超时时间30秒

// 将axios挂载到Vue原型上
Vue.prototype.$axios = axios

// 添加请求拦截器
axios.interceptors.request.use(
  config => {
    // 如果有token，添加到请求头
    const token = localStorage.getItem('token')
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 添加响应拦截器
axios.interceptors.response.use(
  response => {
    return response
  },
  error => {
    if (error.response) {
      // 处理401未授权的情况
      if (error.response.status === 401) {
        // 检查是否是修改密码的请求
        const isChangePasswordRequest = error.config.url.includes('/api/change_password/');
        if (isChangePasswordRequest) {
          // 如果是修改密码请求，返回一个格式化的响应
          return Promise.resolve({
            data: {
              code: 401,
              msg: error.response.data.msg || '原密码不正确'
            }
          });
        } else {
          // 如果不是修改密码请求，进行重定向
          router.push('/login')
        }
      }
    }
    return Promise.reject(error)
  }
)

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>'
})
